package vn.student.message;

import vn.student.database.SQLDataHelper;
import vn.student.notificationforandroid.MainActivity;
import vn.student.notificationforandroid.R;
import vn.student.util.Time;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;

public class DownloadService extends Service
{
    private static final String ID_KEY = "id";
    private static final String COMPLETE = "complete";
    private static final String ACCOUNT = "Account";
    private static final String REGISTERID = "registerid";
    
    private static final String TAG=DownloadService.class.getSimpleName();
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
	String id = intent.getStringExtra(ID_KEY);
	new Message().execute(getRegisterID(),id);
	return super.onStartCommand(intent, flags, startId);
    }
    
    @Override
    public IBinder onBind(Intent arg0)
    {
	return null;
    }
    
    private String getRegisterID()
    {
	SharedPreferences sp = getSharedPreferences(ACCOUNT, MODE_PRIVATE);
	return sp.getString(REGISTERID, "xuantung");
    }
    
    private class Message extends AsyncTask<String, Void, Boolean>
    {
	private String msg = "";
	@Override
	protected Boolean doInBackground(String... params)
	{
	    Log.d(TAG+"1",params[0]);
	    Log.d(TAG+"2",params[1]);
	    ServiceHelper sHelper = new ServiceHelper();
	    // 0= registerid
	    // 1=id
	    try
	    {
		msg = sHelper.getMsg(params[0], Integer.valueOf(params[1]));
		return true;
	    }
	    catch (Exception e)
	    {
		return false;
	    }
	}
	
	@Override
	protected void onPostExecute(Boolean result)
	{
	    super.onPostExecute(result);
	    if (result)
	    {
		//xu ly khi nhan duoc tin, thong bao' tin cho nguoi su dung
		ParseJSON pJSON=new ParseJSON(msg);
		//Thong bao len thanh notification bar
		notifyMessage(getApplicationContext(), pJSON.getContent(Constants.TITLE_MESSAGE), pJSON.getContent(Constants.CONTENT_MESSAGE));
		Log.d(TAG,"Message="+msg);
		//Luu thong bao vao database
		SQLDataHelper sql=new SQLDataHelper(getApplicationContext());
		sql.open();
		sql.insertThongBao(pJSON.getContent(Constants.ID_MESSAGE), pJSON.getContent(Constants.TITLE_MESSAGE), pJSON.getContent(Constants.PUBLISHDATE_MESSAGE), new Time().getTimeReceivedMessage(),  pJSON.getContent(Constants.CONTENT_MESSAGE), 0);
		sql.close();
	    }
	    else
	    {
	    	Log.d(TAG,"Khong lay duoc tin theo id");
		//xu ly khi nhan du lieu loi, phai luu lai trang thai de khi co mang se tiep tuc lay tin
	    }
	    Intent intent=new Intent(Constants.CLASS_DOWNLOADSERVICEMANAGER);
	    intent.putExtra(ID_KEY,COMPLETE);
	    startService(intent);
	}
    }
    private void notifyMessage(Context context, String title,String message) {
        int icon = R.drawable.ic_launcher;
        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(icon, title, when);
        Intent notificationIntent = new Intent(context, MainActivity.class);
        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent =
                PendingIntent.getActivity(context, 0, notificationIntent, 0);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(0, notification);
    }
    
}
